<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input type="text" v-model.trim="name" />
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" v-model.trim.number="age" />
    </div>
    <div>
      <span>性别:</span>
      <select v-model="from">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="tj">添加/修改</button>
      <!-- <button @click="xg">修改</button> -->
    </div>
    <div>
      <table border="1" cellpadding="10" cellspacing="0">
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="(item, index) in list" :key="item.id">
          <td>{{ item.id }}</td>
          <td>{{ item.name }}</td>
          <td>{{ item.age }}</td>
          <td>{{ item.sex }}</td>
          <td>
            <button @click="sc(index)">删除</button>
            <button @click="bj(index)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      name: "",
      age: "",
      from: "",
      myindex: "",
      list: JSON.parse(localStorage.getItem("data")) || [],
      // list: [{ id: 1, name: "wss", age: 18, sex: "男" }],
      bian: true,
    };
  },
  methods: {
    tj() {
      if (this.name.length == 0 || this.age.length == 0) {
        alert("内容不能为空");
        return;
      } else if (this.bian) {
        this.list.push({
          // id: this.list[this.list.length - 1].id + 1,
          id: this.list.length + 1,
          name: this.name,
          age: this.age,
          sex: this.from,
        });
        this.name = "";
        this.age = "";
        this.sex = "";
      } else if (this.bian == false) {
        this.list[this.myindex].name = this.name;
        this.list[this.myindex].age = this.age;
        this.list[this.myindex].sex = this.from;
        console.log(this.name);
        this.bian = true;
        this.name = "";
        this.age = "";
        this.sex = "";
      }
    },
    sc(index) {
      this.list.splice(index, 1);
    },
    bj(index) {
      console.log(index);
      this.name = this.list[index].name;
      this.age = this.list[index].age;
      this.from = this.list[index].sex;
      this.myindex = index;
      this.bian = false;
    },
    // xg() {
    //   this.$set(this.list, this.myindex, {
    //     id: this.myindex + 1,
    //     name: this.name,
    //     age: this.age,
    //     sex: this.from,
    //   });
    // },
  },
  // 侦听器**
  watch: {
    list: {
      handler(newVal) {
        localStorage.setItem("data", JSON.stringify(newVal));
      },
      immediate: true,
      deep: true,
    },
  },
};
</script>

<style>
</style>